package com.neusoft.zqygbc.neusoft_wenda.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.neusoft.zqygbc.neusoft_wenda.R;
import com.neusoft.zqygbc.neusoft_wenda.base.RetrofitCallback;
import com.neusoft.zqygbc.neusoft_wenda.javeBean.Uid;
import com.neusoft.zqygbc.neusoft_wenda.javeBean.User;
import com.neusoft.zqygbc.neusoft_wenda.model.UserModel;
import com.neusoft.zqygbc.neusoft_wenda.service.UserService;
import com.neusoft.zqygbc.neusoft_wenda.utils.BaiduPushUtils;
import com.tencent.connect.UserInfo;
import com.tencent.connect.auth.QQToken;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONException;
import org.json.JSONObject;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class LoginActivity extends BaseAvtivity {

    SharedPreferences sp;
    private TextView btn_reg;
    private Button btn_login;
    private EditText et_utel;
    private EditText et_password;
    private CheckBox login_checkBox;
    private UserModel userModel;
    private Call call;
    private ImageView qq_login;
    private Tencent mTencent;
    private String openidString;


    public void initViews() {
        setLayout(R.layout.activity_login);
        btn_reg = (TextView) findViewById(R.id.btn_login_reg);
        btn_login = (Button) findViewById(R.id.btn_login);
        et_utel = (EditText) findViewById(R.id.login_utel);
        et_password = (EditText) findViewById(R.id.login_password);
        login_checkBox = (CheckBox) findViewById(R.id.login_checkBox);
        qq_login = (ImageView) findViewById(R.id.qq_login);
        sp = getSharedPreferences("userinfo", MODE_PRIVATE);

    }

    public void initData() {
        readSP();

    }

    public void initEvents() {
        btn_reg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(LoginActivity.this, VerifyActivity.class);
                startActivityForResult(intent, 1);

            }
        });
        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getdata();

            }
        });

        //QQ第三方登录
        mTencent = Tencent.createInstance("1106116383", getApplicationContext());
        qq_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTencent.login(LoginActivity.this, "all", new BaseUiListener());

            }
        });


    }

    private class BaseUiListener implements IUiListener {


        public void onComplete(Object response) {
            // TODO Auto-generated method stub
            Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_SHORT).show();
            try {
                //获得的数据是JSON格式的，获得你想获得的内容
                //如果你不知道你能获得什么，看一下下面的LOG
                Log.v("----TAG--", "-------------" + response.toString());
                openidString = ((JSONObject) response).getString("openid");
                mTencent.setOpenId(openidString);
                //saveUser("44","text","text",1);
                mTencent.setAccessToken(((JSONObject) response).getString("access_token"), ((JSONObject) response).getString("expires_in"));
                Log.v("TAG", "-------------" + openidString);
                //access_token= ((JSONObject) response).getString("access_token");              //expires_in = ((JSONObject) response).getString("expires_in");
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            /**到此已经获得OpneID以及其他你想获得的内容了
             QQ登录成功了，我们还想获取一些QQ的基本信息，比如昵称，头像什么的，这个时候怎么办？
             sdk给我们提供了一个类UserInfo，这个类中封装了QQ用户的一些信息，我么可以通过这个类拿到这些信息
             如何得到这个UserInfo类呢？  */

            QQToken qqToken = mTencent.getQQToken();
            UserInfo info = new UserInfo(getApplicationContext(), qqToken);

            //    info.getUserInfo(new BaseUIListener(this,"get_simple_userinfo"));
            info.getUserInfo(new IUiListener() {
                @Override
                public void onComplete(Object o) {

                    try {
                        //用户信息获取到了
                        saveQQUser(openidString, ((JSONObject) o).getString("nickname"), ((JSONObject) o).getString("figureurl_qq_2"), ((JSONObject) o).getString("gender"));
                        Log.v("UserInfo", o.toString());
                        Toast.makeText(LoginActivity.this,o.toString(),Toast.LENGTH_SHORT).show();
                        Intent intent1 = new Intent(LoginActivity.this, MainActivity.class);
                        startActivity(intent1);
                        finish();
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }

                @Override
                public void onError(UiError uiError) {
                    Log.v("UserInfo", "onError");
                }

                @Override
                public void onCancel() {
                    Log.v("UserInfo", "onCancel");
                }
            });


        }

        @Override
        public void onError(UiError uiError) {
            Toast.makeText(getApplicationContext(), "onError", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel() {
            Toast.makeText(getApplicationContext(), "onCancel", Toast.LENGTH_SHORT).show();
        }


    }


    private void getdata() {
        userModel = new UserModel();
        call = userModel.login(et_utel.getText().toString(), et_password.getText().toString());
        RetrofitCallback<Uid> callback = new RetrofitCallback<Uid>() {
            @Override
            public void onResponse(Uid arg0) {
                String utel = et_utel.getText().toString();
                String pwd = et_password.getText().toString();
                Uid uid = arg0;
                if (uid.getUid().equals("0")) {
                    Toast.makeText(LoginActivity.this, "手机号或密码错误", Toast.LENGTH_SHORT).show();
                } else {
                    if (utel.equals("") || pwd.equals("")) {
                        Toast.makeText(LoginActivity.this, "请输入手机号和密码", Toast.LENGTH_SHORT).show();
                    } else {
                        String user_id = uid.getUid();
                        saveSP();
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putString("user_id", user_id);
                        editor.commit();
                        // 启动百度push
                        PushManager.startWork(getApplicationContext(), PushConstants.LOGIN_TYPE_API_KEY,
                                BaiduPushUtils.getMetaValue(LoginActivity.this, "api_key"));
                        //百度推送绑定设备
                        // Push: 无账号初始化，用api key绑定
                        PushManager.startWork(getApplicationContext(),
                                PushConstants.LOGIN_TYPE_API_KEY,
                                BaiduPushUtils.getMetaValue(LoginActivity.this, "api_key"));
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);//传用户Id
                        startActivity(intent);
                        finish();
                    }
                }


            }
        };
        userModel.bindCallback(call, callback);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Tencent.onActivityResultData(requestCode, resultCode, data, new BaseUiListener());

        if (requestCode == Constants.REQUEST_API) {
            if (resultCode == Constants.REQUEST_LOGIN) {
                Tencent.handleResultData(data, new BaseUiListener());
            }
        }


        if (requestCode == 1 && resultCode == RESULT_OK) {
            String Utel = data.getStringExtra("utel");
            et_utel.setText(Utel);
        }
    }

    protected void saveSP() {
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("Utel", et_utel.getText().toString());
        editor.putString("pwd", et_password.getText().toString());
        editor.putBoolean("remember", login_checkBox.isChecked());
        editor.commit();
    }

    private void readSP() {
        String Utel = sp.getString("Utel", null);
        String pwd = sp.getString("pwd", null);
        Boolean rm = sp.getBoolean("remember", false);
        if (rm) {
            et_utel.setText(Utel);
            et_password.setText(pwd);
            login_checkBox.setChecked(true);
        } else {
            login_checkBox.setChecked(false);
        }
    }


    private void saveQQUser(String openidString, String nickname, String figureurl_qq_2, String gender) {

    }

}
